package random.fox.p2p;

import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;

import com.google.gson.Gson;

import butterknife.ButterKnife;
import butterknife.InjectView;
import de.greenrobot.event.EventBus;
import flow.ActivityFlowSupport;
import flow.Backstack;
import flow.Flow;
import flow.path.Path;
import random.fox.p2p.event.ActionBarEvent;
import random.fox.p2p.event.DrawLayoutEvent;
import random.fox.p2p.event.FinishActivityEvent;
import random.fox.p2p.event.GetPicEvent;
import random.fox.p2p.event.MenuClickEvent;
import random.fox.p2p.event.PickPicEvent;
import random.fox.p2p.event.ProgressEvent;
import random.fox.p2p.pathview.GsonParceler;
import random.fox.p2p.pathview.HandlesBack;
import random.fox.p2p.pathview.IndexPathContainerView;
import random.fox.p2p.ui.MenuView;
import random.fox.p2p.util.Util;

/**
 * 主界面的承载Activity
 * Created by wq on 15/3/14.
 */
public class IndexActivity extends ActionBarActivity implements Flow.Dispatcher {

    private final String TAG = "IndexActivity";
    private ActivityFlowSupport flowSupport;

    @InjectView(R.id.content_frame)
    IndexPathContainerView container;
    @InjectView(R.id.drawer_layout)
    DrawerLayout drawerLayout;
    @InjectView(R.id.left_drawer)
    MenuView menuView;

    private HandlesBack containerAsBackTarget;
    private ProgressDialog progressDialog;


    private int menu_layout;
    private Uri fileUri;
    private Uri cropUri;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setType(Window.FEATURE_NO_TITLE);
        GsonParceler parceler = new GsonParceler(new Gson());
        Backstack defaultBackstack = Backstack.single(new Paths.IndexPath());
        @SuppressWarnings("deprecation") ActivityFlowSupport.NonConfigurationInstance nonConfig =
                (ActivityFlowSupport.NonConfigurationInstance) getLastNonConfigurationInstance();
        flowSupport =
                ActivityFlowSupport.onCreate(nonConfig, getIntent(), savedInstanceState, parceler,defaultBackstack);

        setContentView(R.layout.activity_index);

        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("加载中...");

        ButterKnife.inject(this);
        containerAsBackTarget = (HandlesBack) container;
        EventBus.getDefault().register(this);
    }

    /**
     * 通过event,设置ActionBar
     *
     * @param event
     */
    public void onEvent(ActionBarEvent event) {
        Toolbar toolbar = event.getToolbar();

        menu_layout = event.getMenu_layout();

        setSupportActionBar(toolbar);
        ActionBar supportActionBar = getSupportActionBar();
        supportActionBar.setDisplayHomeAsUpEnabled(true);
        supportActionBar.setHomeButtonEnabled(true);
        onPrepareOptionsMenu(toolbar.getMenu());
        if (event.isLock()) {
            drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
            toolbar.setNavigationOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onBackPressed();
                }
            });
        } else {
            ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.drawer_open,
                    R.string.drawer_close);
            mDrawerToggle.syncState();
            drawerLayout.setDrawerListener(mDrawerToggle);
            drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
        }
    }

    public void onEvent(ProgressEvent event){
        if (event.isShow() && progressDialog!= null)
            progressDialog.show();
        else
            progressDialog.dismiss();
    }

    public void onEvent(DrawLayoutEvent event) {
        if (event.isClose()) {
            drawerLayout.closeDrawers();
        }
    }

    public void onEvent(FinishActivityEvent event){
        finish();
    }


    public void onEvent(PickPicEvent event){
        if (event.getType() == Util.CAMERA){
            fileUri = Util.getOutputMediaFileUri();
            Util.getPicByCamera(this,fileUri);
        }else if (event.getType() == Util.GALLERY){
            fileUri = Util.getOutputMediaFileUri();
            Util.getPicByGallery(this);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == Util.CAMERA){
            if (resultCode == RESULT_OK) {
                cropUri = Util.getOutputMediaFileUri();
                Util.cropPic(this,5 ,3 , 500 , 300 , fileUri,cropUri);
            }else {
                Log.d(TAG, "拍照,但没有获得图片");
            }
        }else if (requestCode == Util.GALLERY){
            if (resultCode == RESULT_OK){
                fileUri = data.getData();
                cropUri = Util.getOutputMediaFileUri();
                Util.cropPic(this,5 ,3, 500 , 300, fileUri,cropUri);
            }else {
                Log.d(TAG,"取消了图片选择");
            }
        }else if (requestCode == Util.CROP){
            if (resultCode == RESULT_OK) {
                EventBus.getDefault().post(new GetPicEvent(Util.getFileFromUri(this,cropUri)));
            }else {
                Log.d(TAG,"没有进行图片剪切");
            }
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        flowSupport.onNewIntent(intent);
    }

    @Override
    protected void onResume() {
        super.onResume();
        flowSupport.onResume(this);
    }

    @Override
    protected void onPause() {
        flowSupport.onPause();
        super.onPause();
    }

    @Override
    public Object getSystemService(String name) {
        Object service = null;
        if (flowSupport != null) {
            service = flowSupport.getSystemService(name);
        }
        return service != null ? service : super.getSystemService(name);
    }

    @Override
    public void onBackPressed() {
        if (containerAsBackTarget.onBackPressed()) return;
        if (flowSupport.onBackPressed()) return;
        super.onBackPressed();
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        if (menu_layout > 0) {
            menu.clear();
            getMenuInflater().inflate(menu_layout, menu);
            return true;
        }
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_index, menu);
//        MenuItem menuItem = menu.findItem(R.id.menu_search);
//        if (menuItem != null) {
//            SearchView searchView = (SearchView) MenuItemCompat.getActionView(menuItem);
//        }
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case R.id.add_message_menu:
                EventBus.getDefault().post(new MenuClickEvent());
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void dispatch(Flow.Traversal traversal, final Flow.TraversalCallback callback) {
        Path path = traversal.destination.current();
        setTitle(path.getClass().getSimpleName());
        android.support.v7.app.ActionBar actionBar = getSupportActionBar();
        boolean canGoBack = traversal.destination.size() > 1;
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(canGoBack);
            actionBar.setHomeButtonEnabled(canGoBack);
        }
        container.dispatch(traversal, new Flow.TraversalCallback() {
            @Override
            public void onTraversalCompleted() {
                invalidateOptionsMenu();
                callback.onTraversalCompleted();
            }
        });
    }
    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }
}
